package com.cjj2016.cjj.mylyricviewdemo;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cjj2016.cjj.mylyricviewdemo.model.LineInfo;
import com.cjj2016.cjj.mylyricviewdemo.model.LyricInfo;
import com.cjj2016.cjj.mylyricviewdemo.util.DisplayUtil;
import com.cjj2016.cjj.mylyricviewdemo.util.HttpUtil;
import com.cjj2016.cjj.mylyricviewdemo.widget.MyFloatView;
import com.cjj2016.cjj.mylyricviewdemo.widget.MyLyricView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";

    //刷新消息
    private static final int MSG_REFRESH = 1;

    //显示消息
    private static final int MSG_LYRIC_SHOW = 2;
    private static final int MSG_LOADING = 3;


    //状态值
    private enum State{
        STATE_STOP,STATE_PLAYING,STATE_PAUSE,STATE_SETUP,STATE_PREPARE
    }

    private State currentState = State.STATE_STOP;

    private MyLyricView myLyricView;

    private long timeval = 0;

    private int level;
    private Runnable runnable;

    //上一首，播放，下一首Imageview
    private ImageView ivPrev,ivPlay,ivNext;

    private ValueAnimator pressAnim;//按钮按下动画
    private ValueAnimator upAnimator;//弹起动画

    private MediaPlayer mediaPlayer;

    private TextView tv_musicName;
    private TextView tv_startTime;
    private TextView tv_endTime;
    private SeekBar seekBar;

    private String mp3url = Environment.getExternalStorageDirectory() + "/dangni.mp3";

    //歌曲名
    private String[] songNames;

    //歌曲mp3路径
    private String[] songUrls;

    //歌词路径
    private String[] songLrcs;

    //歌曲位置，默认为0
    private int SongPosition=0;

    //是否加载状态
    private boolean mLoading;

    private View floatView;

    private View menuView;

    private MyFloatView myFloatView;

    private TextView menuSongTitle;
    private TextView menuStartTime;
    private TextView menuEndtime;
    private SeekBar menuSeekbar;
    private ImageButton menubtnPre,menubtnPlay,menubtnNext;


    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_LYRIC_SHOW:

                    setCurrentState(State.STATE_SETUP);
                    try {
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(songUrls[SongPosition]);
                        mediaPlayer.prepareAsync();
                       //播放准备完成
                        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                setCurrentState(State.STATE_PREPARE);
                                DecimalFormat format = new DecimalFormat("00");
                                seekBar.setMax(mp.getDuration());
                                String formattime = format.format(mp.getDuration() / 1000 / 60) + ":" + format.format(mp.getDuration() / 1000 % 60);
                                tv_endTime.setText(formattime);
                                menuSeekbar.setMax(mp.getDuration());
                                menuEndtime.setText(formattime);
                                start();
                            }
                        });
                        //播放完成
                        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                next();
                               // Log.i(TAG, "onCompletion: bofangwancengle");
                            }
                        });
                        //缓冲监听
                        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                            @Override
                            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                                seekBar.setSecondaryProgress((int) (mp.getDuration() * 1.00f * percent / 100.0f));
                                menuSeekbar.setSecondaryProgress((int) (mp.getDuration() * 1.00f * percent / 100.0f));
                            }
                        });
                        //发生错误监听
                        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                            @Override
                            public boolean onError(MediaPlayer mp, int what, int extra) {
                                //Log.i(TAG, "onError: exec;"+"what="+what+","+"extra="+ extra );
                                return true;
                            }
                        });


                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case MSG_REFRESH:
                    if( mediaPlayer!=null){
                        myLyricView.setCurrentTime( mediaPlayer.getCurrentPosition() );
                        DecimalFormat format = new DecimalFormat("00");
                        seekBar.setProgress(mediaPlayer.getCurrentPosition());
                        String formattime = format.format(mediaPlayer.getCurrentPosition() / 1000 / 60) + ":" + format.format(mediaPlayer.getCurrentPosition() / 1000 % 60);
                        tv_startTime.setText(formattime);
                        menuSeekbar.setProgress(mediaPlayer.getCurrentPosition());
                        menuStartTime.setText(formattime);
                    }

                    //延迟120ms，发送刷新消息。
                    handler.sendEmptyMessageDelayed(MSG_REFRESH,120);
                    break;
                case MSG_LOADING:
                    Drawable drawable = ivPlay.getBackground();
                    int level = drawable.getLevel();
                    level = level + 300;
                    if(level > 10000){
                        level = level -10000;
                    }
                    drawable.setLevel(level);
                    handler.sendEmptyMessageDelayed(MSG_LOADING,50);
                    break;
            }
        }
    };





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DisplayUtil.hideStatusBar(getWindow());
        setContentView(R.layout.activity_main);

        myLyricView = (MyLyricView) findViewById(R.id.myLyricView_mainAct);
        myLyricView.setInvaldatePlayListener(new MyLyricView.invaldatePlayListener() {
            @Override
            public void playTime(long time) {
                if(mediaPlayer!=null && (currentState==State.STATE_PLAYING || currentState==State.STATE_PAUSE) ){
                    mediaPlayer.seekTo((int) time);
                    if(currentState==State.STATE_PAUSE){
                        start();
                    }
                }
            }
        });

        tv_musicName= (TextView) findViewById(R.id.tv_musicName_mainAct);
        tv_startTime= (TextView) findViewById(R.id.tv_startTime_mainAct);
        tv_endTime= (TextView) findViewById(R.id.tv_endTime_mainAct);
        seekBar = (SeekBar) findViewById(R.id.seekbar_mainAct);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    DecimalFormat format = new DecimalFormat("00");
                    tv_startTime.setText(format.format(progress / 1000 / 60) + ":" + format.format(progress / 1000 % 60));
                    menuStartTime.setText(format.format(progress / 1000 / 60) + ":" + format.format(progress / 1000 % 60));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                handler.removeMessages(MSG_REFRESH);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mediaPlayer.seekTo(seekBar.getProgress());
                handler.sendEmptyMessage(MSG_REFRESH);
            }
        });


        ivPrev = (ImageView) findViewById(R.id.iv_prev_mainAct);
        ivPrev.setOnClickListener(this);
        ivNext = (ImageView) findViewById(R.id.iv_next_mainAct);
        ivNext.setOnClickListener(this);


        ivPlay = (ImageView) findViewById(R.id.iv_play_mainAct);
        ivPlay.setOnClickListener(this);

        initData();

        initMyFloatView();

        mediaPlayerSetup();



    }



    //init数据
    private void initData() {
        //从strings文件中获取数据
        songNames = getResources().getStringArray(R.array.song_names);
        songUrls = getResources().getStringArray(R.array.song_urls);
        songLrcs = getResources().getStringArray(R.array.song_lrcs);
    }


    private void mediaPlayerSetup() {
        //设置歌曲名
        tv_musicName.setText( songNames[SongPosition] );

        //floatview中的歌曲名
        menuSongTitle.setText(songNames[SongPosition]);

        handler.removeMessages(MSG_LYRIC_SHOW);
        handler.sendEmptyMessage(MSG_LYRIC_SHOW);
    }

    //设置当前状态
    private void setCurrentState(State state){
        if (state == currentState){
            return;
        }
        currentState = state;
        switch (state){
            case STATE_SETUP:
                //设置歌词文件
                String lrcPath = MainActivity.this.getExternalCacheDir() + "/"+ songNames[SongPosition]+".lrc";
                File lrcfile = new File(lrcPath);
                if(lrcfile.exists()){
                    try {
                        LyricInfo lyricInfo = setupLyricResource(new FileInputStream(lrcfile),"GBK");
                        myLyricView.setLyricInfo(lyricInfo);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }else {
                    //下载歌词，并缓存到本地
                    downloadLrc(songLrcs[SongPosition],lrcfile);
                }

                //设置播放按钮图片
                ivPlay.setImageResource(R.mipmap.m_icon_player_play_normal);
                setLoading(true);
                menubtnPlay.setImageResource(R.mipmap.landscape_player_btn_play_press);
                break;
            case STATE_PREPARE:
                setLoading(false);
                break;
            case STATE_PLAYING:
                //设置暂停按钮图片
                ivPlay.setImageResource(R.mipmap.m_icon_player_pause_normal);
                menubtnPlay.setImageResource(R.mipmap.landscape_player_btn_pause_normal);
                break;
            case STATE_PAUSE:
                //设置播放按钮图片
                ivPlay.setImageResource(R.mipmap.m_icon_player_play_normal);
                menubtnPlay.setImageResource(R.mipmap.landscape_player_btn_play_press);
                break;
            case STATE_STOP:
                //缓冲进度条，还原为0
                seekBar.setSecondaryProgress(0);
                seekBar.setProgress(0);
                tv_startTime.setText("00:00");
                tv_endTime.setText("--:--");
                //设置播放按钮图片
                ivPlay.setImageResource(R.mipmap.m_icon_player_play_normal);
                setLoading(false);

                menuSeekbar.setSecondaryProgress(0);
                menuSeekbar.setProgress(0);
                menuStartTime.setText("00:00");
                menuEndtime.setText("--:--");
                menubtnPlay.setImageResource(R.mipmap.landscape_player_btn_play_press);
                break;

        }
    }


    //开始播放
    private void start() {
        if(mediaPlayer !=null &&
                (currentState == State.STATE_PAUSE || currentState == State.STATE_PREPARE))
        {
            setCurrentState(State.STATE_PLAYING);
            mediaPlayer.start();
            handler.sendEmptyMessage(MSG_REFRESH);
        }
    }

    //暂停
    private void pause() {
        if(mediaPlayer!=null){
            setCurrentState(State.STATE_PAUSE);
            mediaPlayer.pause();
            handler.removeMessages(MSG_REFRESH);
        }
    }

    //上一首
    private void previous() {
        stop();
        SongPosition --;
        if(SongPosition <= 0){
            SongPosition= songUrls.length-1;
        }

        mediaPlayerSetup();
    }

    //下一首
    private void next() {
        stop();
        SongPosition ++;
        if(SongPosition >= songUrls.length){
            SongPosition=0;
        }

        mediaPlayerSetup();
    }

    //停止
    private void stop(){
        if(mediaPlayer != null && mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;
        }
        handler.removeMessages(MSG_REFRESH);
        myLyricView.reset("正在载入中...");
        setCurrentState(State.STATE_STOP);
    }


    /**
     * 设置按钮加载状态
     */
    private void setLoading(boolean load){
        if(load && !mLoading){
            ivPlay.setBackgroundResource(R.drawable.rotate_player_loading);
            handler.sendEmptyMessageDelayed(MSG_LOADING,200);
            mLoading = true;
            return;
        }

        if( !load && mLoading){
            handler.removeMessages(MSG_LOADING);
            ivPlay.setBackgroundColor(Color.TRANSPARENT);
            mLoading= false;
            return;
        }
    }

    @Override
    public void onClick(View v) {

        if(pressAnim !=null && pressAnim.isRunning())
        {
            pressAnim.cancel();
        }

        if(upAnimator !=null && upAnimator.isRunning())
        {
            upAnimator.cancel();
        }

        switch (v.getId()){
            case R.id.iv_prev_mainAct:
                previous();
                break;
            case R.id.iv_play_mainAct:
                if(currentState == State.STATE_PLAYING){
                    pause();
                    break;
                }
                if(currentState == State.STATE_PAUSE){
                    start();
                }

                break;
            case R.id.iv_next_mainAct:
                next();

                break;
        }

        pressAnim =  pressAnimation(v);
        pressAnim.start();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        stop();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            //按返回键时，程序不退出，退回到后台
            moveTaskToBack(true);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    //下载歌词文件
    private void downloadLrc(String songLrcUrl, final File lrcfile) {
        HttpUtil.downloadFile(songLrcUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(MainActivity.this, "下载歌词，失败！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                byte[] lrcbytes = response.body().bytes();

                try {
                    //保存文件到缓存目录中
                    FileOutputStream fileOutputStream = new FileOutputStream(lrcfile);
                    fileOutputStream.write(lrcbytes);
                    fileOutputStream.close();

                    //把歌词设置给myLyricView
                    LyricInfo lyricInfo = setupLyricResource(new FileInputStream(lrcfile),"GBK");
                    myLyricView.setLyricInfo(lyricInfo);

                }catch (Exception ex){
                    ex.printStackTrace();
                }

            }
        });
    }



    //按钮按下动画
    private ValueAnimator pressAnimation(final View v) {
        final float size = v.getScaleX();
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(size, size* 0.7f).setDuration(120);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float animval = (Float) animation.getAnimatedValue();
                v.setScaleX(animval);
                v.setScaleY(animval);
            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                //动画结束，执行弹起动画
                upAnimator = upValueAnimator(v);
                upAnimator.start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                v.setScaleX(size* 0.7f);
                v.setScaleY(size* 0.7f);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        return valueAnimator;

    }

    //按钮弹起动画
    private ValueAnimator upValueAnimator(final View view){

        final float size = view.getScaleX();
        ValueAnimator valueAnimator1 = ValueAnimator.ofFloat( size, size / 0.7f);
        valueAnimator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float animval2 = (float) animation.getAnimatedValue();
                view.setScaleX(animval2);
                view.setScaleY(animval2);
            }
        });
        valueAnimator1.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {
                view.setScaleX( size/0.7f );
                view.setScaleY( size/0.7f );
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        valueAnimator1.setDuration(120);

        return valueAnimator1;
    }







    /**
     * 初始化歌词信息
     * @param inputStream  歌词文件的流信息
     * */
    private LyricInfo setupLyricResource(InputStream inputStream, String charsetName) {
        if(inputStream != null) {
            try {
                LyricInfo lyricInfo = new LyricInfo();
                lyricInfo.song_lines = new ArrayList<>();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charsetName);
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String line = null;
                while((line = reader.readLine()) != null) {
                    analyzeLyric(lyricInfo, line);
                }
                reader.close();
                inputStream.close();
                inputStreamReader.close();

                return lyricInfo;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * 逐行解析歌词内容
     * */
    private void analyzeLyric(LyricInfo lyricInfo, String line) {
        int index = line.lastIndexOf("]");
        if(line != null && line.startsWith("[offset:")) {
            // 时间偏移量
            String string = line.substring(8, index).trim();
            lyricInfo.song_offset = Long.parseLong(string);
            return;
        }
        if(line != null && line.startsWith("[ti:")) {
            // title 标题
            String string = line.substring(4, index).trim();
            lyricInfo.song_title = string;
            return;
        }
        if(line != null && line.startsWith("[ar:")) {
            // artist 作者
            String string = line.substring(4, index).trim();
            lyricInfo.song_artist = string;
            return;
        }
        if(line != null && line.startsWith("[al:")) {
            // album 所属专辑
            String string = line.substring(4, index).trim();
            lyricInfo.song_album = string;
            return;
        }
        if(line != null && line.startsWith("[by:")) {
            return;
        }
        if(line != null && index == 9 && line.trim().length() > 10) {
            // 歌词内容
            LineInfo lineInfo = new LineInfo();
            lineInfo.content = line.substring(10, line.length());
            lineInfo.start = measureStartTimeMillis(line.substring(0, 10));
            lyricInfo.song_lines.add(lineInfo);
        }
    }

    /**
     * 从字符串中获得时间值
     * */
    private long measureStartTimeMillis(String str) {
        long minute = Long.parseLong(str.substring(1, 3));
        long second = Long.parseLong(str.substring(4, 6));
        long millisecond = Long.parseLong(str.substring(7, 9));
        return millisecond + second * 1000 + minute * 60 * 1000;
    }



    //初始化floatview
    private void initMyFloatView(){
        MyOnclickListener myOnclickListener = new MyOnclickListener();

        //设置按钮
        ImageView ivSetting = (ImageView) findViewById(R.id.iv_setting);
        ivSetting.setOnClickListener(myOnclickListener);


        floatView = LayoutInflater.from(this).inflate(R.layout.layout_float,null);
        menuView = LayoutInflater.from(this).inflate(R.layout.layout_menu,null);
        menuSongTitle = (TextView) menuView.findViewById(R.id.player_displayname);
        menuStartTime = (TextView) menuView.findViewById(R.id.player_progress);
        menuEndtime = (TextView) menuView.findViewById(R.id.player_duration);
        menuSeekbar = (SeekBar) menuView.findViewById(R.id.player_seek);
        menuSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    DecimalFormat format = new DecimalFormat("00");
                    tv_startTime.setText(format.format(progress / 1000 / 60) + ":" + format.format(progress / 1000 % 60));
                    menuStartTime.setText(format.format(progress / 1000 / 60) + ":" + format.format(progress / 1000 % 60));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                handler.removeMessages(MSG_REFRESH);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mediaPlayer.seekTo(seekBar.getProgress());
                handler.sendEmptyMessage(MSG_REFRESH);
            }
        });


        menubtnPre = (ImageButton) menuView.findViewById(R.id.player_previous);
        menubtnPre.setOnClickListener(myOnclickListener);
        menubtnPlay = (ImageButton) menuView.findViewById(R.id.player_play);
        menubtnPlay.setOnClickListener(myOnclickListener);
        menubtnNext = (ImageButton) menuView.findViewById(R.id.player_next);
        menubtnNext.setOnClickListener(myOnclickListener);

        myFloatView = new MyFloatView(this,floatView,menuView);

    }



    class MyOnclickListener implements  View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.iv_setting:
                    if( !myFloatView.getShowing() ){
                        myFloatView.show();
                    }else {
                        myFloatView.hide();
                    }

                    break;
                case R.id.player_previous:
                    previous();
                    break;
                case R.id.player_play:
                    if(currentState == State.STATE_PLAYING){
                        pause();
                        break;
                    }
                    if(currentState == State.STATE_PAUSE){
                        start();
                    }
                    break;
                case R.id.player_next:
                    next();

                    break;
            }
        }
    }

}
